//
//  APPUser.swift
//  AESOLAR_IOS
//
//  Created by Mr.wang on 2019/1/7.
//  Copyright © 2019 Mr.wang. All rights reserved.
//

import UIKit
import HandyJSON
import GoogleSignIn
import FBSDKLoginKit

struct LoginModel: HandyJSON {
    var token = ""
    var type = ""
    var userId = ""
}

enum APPUserState {
    case logOut
    case login(LoginModel)
}

class APPUser: NSObject {
    
    static let shared = APPUser()
    
    fileprivate override init() {
        super.init()
    }
    
    public var state: APPUserState {
        set {
            switch newValue {
            case .login(let loginModel):
                AppCache.shared.cacheObject(object: loginModel)
            case .logOut:
                GIDSignIn.sharedInstance()?.signOut()
                LoginManager().logOut()
                AppCache.shared.removeObject(for: LoginModel.self)
                let path = NSHomeDirectory() + "/Library/Caches/com.moya.cache/"
                try? FileManager.default.removeItem(at: URL.init(fileURLWithPath: path))
            }
        }
        get {
            return !isLogin ? .logOut : .login(AppCache.shared.object(for: LoginModel.self))
        }
    }
    
    var userInfo: LoginModel {
        get {
            return AppCache.shared.object(for: LoginModel.self)
        }
    }
    
    var token: String {
        get {
            return userInfo.token
        }
    }
    
    var userId: String {
        get {
            return userInfo.userId
        }
    }
    
    var isLogin: Bool {
        get {
            return token.count > 0
        }
    }
    
    func logOut(_ closure: @escaping () -> ()) {
        ApiManager.logOut().request()
            .filterCode200()
            .trackingLoading()
            .subscribe(onNext: { (_) in
                APPUser.shared.state = .logOut
                closure()
            }).disposed(by: rx.disposeBag)
    }
    
}
